package com.efounder.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.ospmobilelib.R;
import com.pansoft.resmanager.ResFileManager;

public class TypedListAdapter extends BaseAdapter {

	private LayoutInflater mInflater;
	final String mType;
	final int mLayoutResource;
	private List<StubObject> mData;

	public TypedListAdapter(Context context, String type, List<StubObject> data) {
		mInflater = LayoutInflater.from(context);
		mType = type;
		mLayoutResource = getLayoutResourceByType(type);
		mData = data;
	}

	/**
	 * menu种类决定布局
	 */
	private int getLayoutResourceByType(String type) {
		if (!TextUtils.isEmpty(type)) {
			final String t = type.toLowerCase().trim();
			// TODO 类型不全
			if (t.equals("shelf")||"menu".equals(t)) {
				return R.layout.listitem_type_shelf;
			}
		}
		return R.layout.listitem_type_normalist;
	}

	/**
	 * 绑定数据
	 */
	private void bindData(View convertView, int position) {
		if (convertView != null && (convertView.getTag() != null)) {
			StubObject menuItem = (StubObject) mData.get(position);
			ViewHolder h = (ViewHolder) convertView.getTag();

			// TODO 类型不全
			if (mType != null) {
				final String t = mType.toLowerCase().trim();
				if (t.equals("shelf")||"display".equals(t)||"menu".equals(t)) {
					// 取menuIcon
					String iconPath = (String) menuItem.getString("menuIcon", null);
					if (!TextUtils.isEmpty(iconPath)) {
						h.icon.setImageBitmap(BitmapFactory.decodeFile(ResFileManager.IMAGE_DIR + "/"
								+ iconPath));
					}
				} else if (t.equals("normallist")) {
				}
			}
			h.text.setText(menuItem.getCaption());
		}
	}

	@Override
	public int getCount() {
		return mData == null ? 0 : mData.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = mInflater.inflate(mLayoutResource, null);
			ViewHolder h = new ViewHolder();
			h.icon = (ImageView) convertView.findViewById(R.id.iv_icon);
			h.text = (TextView) convertView.findViewById(R.id.tv_text);
			convertView.setTag(h);
		}
		bindData(convertView, position);
		return convertView;
	}

	private class ViewHolder {
		private ImageView icon;
		private TextView text;
	}
}